import {config} from '../utils/config.js';

class Token {
    constructor(){
      this.tokenUrl = config.restUrl + 'token';
      this.verifyUrl = config.restUrl +'token/verify';
    }

   /**
    * 首次进入app或者小程序中检测令牌，如果存在令牌在检测可用，如果令牌不存在在生成新的的令牌
    */
    verify(){
      var token = wx.getStorageSync('token');
      if(!token){
        this.getTokenFromServer();
      }else{
        this._setVerifyFromServer(token);
      }
    }

    /**检测令牌不存在时，生成新的令牌 */
    getTokenFromServer(callBack){
        var that = this;
        wx.login({
          success: function (res) {//获取code
          console.log('code:',res.code);
              wx.request({
                url: that.tokenUrl,
                method:'POST',
                data: {
                  code: res.code
                },
                success:function(res){//通过code获取openid 生成令牌

                  wx.setStorageSync('token',res.data.token);
                  callBack && callBack(res.data.token);
                }
              })
          }
        });
    }

    /**携带令牌去服务器校验令牌的可用性 */
    _setVerifyFromServer(token){
        var that = this;
        wx.request({
          url: that.verifyUrl,
          method: 'POST',
          data: {
            token:token
          },
          success: function (res) {
            console.log('res:',res);
            var isValid = res.data.isValid;
            if (!isValid) {//校验通过则过，没有通过则重新成新的token
              that.getTokenFromServer();
            }
          }
        })

    }
}

export {Token};

